//
//  GCHPrivacyAgreementView
//
//  Created by GCH on 2020/5/8.
//  Copyright © 2020 cn.hdcb.com. All rights reserved.
//

#import "GCHPrivacyAgreementView.h"
#import "UILabel+YBAttributeTextTapAction.h"
#import "UIColor+Hex.h"
@interface GCHPrivacyAgreementView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *customTableview;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *sureButton;
@property (nonatomic, strong) UIButton *gouButton;
@property (nonatomic)BOOL gouButtonCheck;
@end

@implementation GCHPrivacyAgreementView

#define contentViewHeigh  465
#define contentViewMargin 30

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [[UIColor colorWithHexString:@"#000000"] colorWithAlphaComponent:0.3];
        self.gouButtonCheck=NO;
        NSString *str=@"  感谢您使用新邻APP，欢迎您点击查看《用户服务协议》和《隐私政策》，您可以通过查阅《个人信息收集清单》及《第三方共享个人信息清单》查阅个人信息搜集情况，如您同意，请点击“同意”并接受我们的服务，感谢您的信任。\n  我们非常重视隐私和个人信息保护，我们基于以下目的收集和使用个人信息:\n  1.基于平台正常运行、信息推送和安全审查的目的，我们可能会申请系统设备权限的方式收集设备信息（包括：硬件型号、设备序列号、操作系统版本号、ios ID、MEID、IMEI、IMSI、OAID、SMID、ICCID、SIM卡信息、设备序列号、MAC地址、软件安装列表、IP地址、WLAN接入点、蓝牙、WIFI的BSSID、本机号码、传感器、基站、软件版本号、操作日志、网络接入方式、网络接入类型、状态、网络质量数据、操作、使用、服务日志信息），以上信息用于信息推送和安全风控；\n  2.基于保障软件与服务的安全运行，确保您和其他用户的账号与财产安全的目的，使您的正当合法权益免受不法侵害，平台内的安全服务商SDK通过申请系统设备权限的方式收集您的必要设备信息、硬件型号、操作系统版本号、传感器数据、应用程序安装列表、国际移动设备识别码（IMEI）、IMSI、OAID、SMID、ICCID、SIM卡信息、设备序列号、网络设备硬件地址（MAC）、ANDROID ID、IP地址、WLAN接入点、WIFI的SSID及BSSID、蓝牙、基站、软件版本号、操作日志、网络接入方式、网络接入类型、状态、网络质量数据、操作、使用、服务日志信息;\n 3.为保证您可以使用本产品发生、接受、缓存、下载图片视频类文件、我们可能会通过申请系统设备权限的方式获取存储权限，用于下载及缓存相关文件;\n  4.为了方便用户更好的复制站内的信息并用在其他站外场景，平台以及SDK通过申请系统设备权限的方式获取剪切板权限；\n  5.摄像头、麦克风、相册、存储空间、GPS这类敏感权限均不会默认或强制开启收集信息，平台会根据需求单独获得您的授权，您可以选择允许或拒绝，都不会影响您使用本平台的其他功能；\n  6.平台仅在您注册、音频推荐、广告推送、发布图文、账号推荐、互动交流、搜索、查询、认证、虚拟财产场景相关时收集与使用您的上述个人信息。未经您同意，我们不会出售或出租您的任何信息；\n  7.您可以访问、更正、删除个人信息，也可以联系我们进行账户注销、更正和投诉处理。";
//        self.dataArray =@[@"       我们希望通过《用户服务协议》（下称“协议”)和《新邻隐私政策》来帮助您了解我们为您提供的服务，及收集、处理您个人信息的相应规则。\n      为向您提供特定服务或功能，我们会以弹窗形式、在征得您同意后获取特定权限和信息。拒绝授权仅会使得您无法使用其对应的特定服务或功能，但不影响您使用我们的其他服务。\n      设备信息：经您授权后，我们申请政权限，用于识别设备，进行信息推送和安全保证等服务\n      相机相册：经您授权后，使用拍照、上传照片、音视频聊夭和直播等对应服务时\n      录音：经您授权后，使用录制语音信息、音视频聊天、直播等对应服务时存储：经您授权后，下载或保存等对应服务时\n      网络：经您授权后,访问网络、获取网络状态、改变wifi开关状态时\n      地理位置：经您授权后，使用基于地理位置的服务、在特定场景申请或展示地理位置时\n      如您已阅读并同意协议及政策，请点击“同意”。"];
        
        self.dataArray =@[str];
        
        
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder{
    [super encodeWithCoder:coder];
    self.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.5];
    
}

-(void)showPrivacyAgreementView:(UIView*)view{
    [view addSubview:self];
    [self addSubview:self.contentView];
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.customTableview];
    [self addButton];
    
//    [self addCheck];
}
-(void)hiddenPrivacyAgreementView{
    
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdtifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdtifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdtifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.textColor = [UIColor colorWithHexString:@"#333333"];
        cell.textLabel.font = [UIFont systemFontOfSize:17];
        
    }
    cell.textLabel.text=self.dataArray[0];
    cell.textLabel.attributedText = [self getAttributeWith:@[@"《用户服务协议》",@"《隐私政策》",@"《个人信息收集清单》",@"《第三方共享个人信息清单》"] string:self.dataArray[0] orginFont:14 orginColor:[UIColor colorWithHexString:@"#666666"] attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#FF729A"]];
//
    __weak typeof(self)weakSelf = self;
    cell.textLabel.enabledTapEffect = YES;
    [cell.textLabel yb_addAttributeTapActionWithStrings:@[@"《用户服务协议》",@"《隐私政策》",@"《个人信息收集清单》",@"《第三方共享个人信息清单》"] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
        NSLog(@"%ld",(long)index);
        if ([weakSelf.PAdelegate respondsToSelector:@selector(clickPrivacyAgreementIndex:)]) {
            [weakSelf.PAdelegate clickPrivacyAgreementIndex:index];
        }
    }];

    
    return cell;
    
}

- (UIView*)contentView{
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(contentViewMargin, 0, self.bounds.size.width - contentViewMargin*2, contentViewHeigh)];
        _contentView.center = self.center;
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.layer.cornerRadius = 4;
    }
    return _contentView;
}

- (UILabel*)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 26.3, self.contentView.bounds.size.width, 22)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = [UIColor colorWithHexString:@"#333333"];
        _titleLabel.font = [UIFont boldSystemFontOfSize:18];
        _titleLabel.text = @"欢迎使用新邻";
        
    }
    return _titleLabel;
}

- (UITableView *)customTableview{
    if (!_customTableview) {
        _customTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.titleLabel.frame)+10, self.contentView.bounds.size.width, contentViewHeigh - CGRectGetMaxY(self.titleLabel.frame) - 10 - 45-60+60 ) style:UITableViewStylePlain];
        _customTableview.layer.cornerRadius = 10;
        _customTableview.rowHeight = UITableViewAutomaticDimension;
        _customTableview.separatorColor = [UIColor clearColor];
        _customTableview.tableFooterView = [UIView new];
        _customTableview.tableHeaderView = [UIView new];
        _customTableview.delegate = self;
        _customTableview.dataSource = self;
        _customTableview.bounces=NO;
    }
    return _customTableview;
}

- (void)addButton{
    
    CGFloat buttonWidth = self.contentView.bounds.size.width / 2;
    CGFloat buttonHeight = 44;
    CGFloat originY =  self.contentView.bounds.size.height - buttonHeight;

    for (int i =0; i<2; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(i*buttonWidth,originY, buttonWidth, buttonHeight);
        button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 100+i;
        if (i == 1) {
            [button setTitleColor:[UIColor colorWithHexString:@"#FF729A"] forState:UIControlStateNormal];
            [button setTitle:@"同意" forState:UIControlStateNormal];
        }else{
            [button setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
            [button setTitle:@"不同意" forState:UIControlStateNormal];

        }
        [self.contentView addSubview:button];

    }
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, originY, self.contentView.bounds.size.width, 0.5)];
    lineView.backgroundColor = [UIColor colorWithHexString:@"#DFDFDF"];
    [self.contentView addSubview:lineView];

    UIView *middleView = [[UIView alloc] initWithFrame:CGRectMake(self.contentView.bounds.size.width / 2, originY, 0.5, buttonHeight)];
    middleView.backgroundColor = [UIColor colorWithHexString:@"#DFDFDF"];
    [self.contentView addSubview:middleView];
    
    
//    CGFloat buttonWidth = self.contentView.bounds.size.width;
//    CGFloat buttonHeight = 44;
//    CGFloat originY =  self.contentView.bounds.size.height - buttonHeight;
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//    button.frame = CGRectMake(0,originY, buttonWidth, buttonHeight);
//    button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
//    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
//    button.tag = 100;
//    [button setBackgroundColor:[UIColor colorWithHex:0xDBDBDB]];
//    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [button setTitle:@"确定" forState:UIControlStateNormal];
//    [self.contentView addSubview:button];
//
//    self.sureButton=button;
    
    
    //给_stateLab圆角
//    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, buttonWidth, buttonHeight) byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(4, 4)];
//    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//    maskLayer.frame = CGRectMake(0, 0, buttonWidth, buttonHeight);
//    maskLayer.path = maskPath.CGPath;
//    button.layer.mask = maskLayer;
}

-(void)addCheck{
    //170
    UIView *aview=[[UIView alloc]init];
    aview.frame=CGRectMake(self.contentView.bounds.size.width/2-85, self.contentView.bounds.size.height-40-44, 170, 20);
    [self.contentView addSubview:aview];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0,0, 25, 20);
    [button addTarget:self action:@selector(checkButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    [button setBackgroundColor:[UIColor lightGrayColor]];
    [button setImage:[UIImage imageNamed:@"须知未勾选"] forState:UIControlStateNormal];
    [aview addSubview:button];
    self.gouButton=button;
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(25, 0, aview.bounds.size.width-25, 20)];
    lable.textAlignment = NSTextAlignmentRight;
    lable.textColor = [UIColor colorWithHexString:@"#B1B1B1"];
    lable.font = [UIFont fontWithName:@"PingFangSC-Medium" size:13];
    lable.text = @"已阅读且同意并不再提示";
    [aview addSubview:lable];
    
}

-(void)checkButtonClick{
    NSLog(@"checkButtonClick");
    
    if ( self.gouButtonCheck==NO) {
        NSLog(@"须知勾选");
        self.gouButtonCheck=YES;
//        [self.gouButton setBackgroundColor:[UIColor blueColor]];
        [self.sureButton setBackgroundColor:[UIColor colorWithHex:0x64A3FF]];
        [self.gouButton setImage:[UIImage imageNamed:@"须知已勾选"] forState:UIControlStateNormal];
       
    }else{
        self.gouButtonCheck=NO;
//        [self.gouButton setBackgroundColor:[UIColor lightGrayColor]];
        [self.sureButton setBackgroundColor:[UIColor colorWithHex:0xDBDBDB]];
        [self.gouButton setImage:[UIImage imageNamed:@"须知未勾选"] forState:UIControlStateNormal];
    }
}

- (void)buttonClick:(UIButton*)button{
//    if ( self.gouButtonCheck==NO) {
//        NSLog(@"未勾选须知");
//        return;
//    }
    
    [self hiddenPrivacyAgreementView];
    if ([self.PAdelegate respondsToSelector:@selector(clickButton:withView:)]) {
        [self.PAdelegate clickButton:button.tag withView:self];
    }
}

- (NSAttributedString *)getAttributeWith:(id)sender
                                  string:(NSString *)string
                               orginFont:(CGFloat)orginFont
                              orginColor:(UIColor *)orginColor
                           attributeFont:(CGFloat)attributeFont
                          attributeColor:(UIColor *)attributeColor
{
    __block  NSMutableAttributedString *totalStr = [[NSMutableAttributedString alloc] initWithString:string];
    [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:orginFont] range:NSMakeRange(0, string.length)];
    [totalStr addAttribute:NSForegroundColorAttributeName value:orginColor range:NSMakeRange(0, string.length)];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:3.0f]; //设置行间距
    paragraphStyle.firstLineHeadIndent=orginFont * 2;
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
    paragraphStyle.alignment = NSTextAlignmentJustified;
    [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
    [totalStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [totalStr length])];
    
    if ([sender isKindOfClass:[NSArray class]]) {
        
        __block NSString *oringinStr = string;
        __weak typeof(self) weakSelf = self;
        
        [sender enumerateObjectsUsingBlock:^(NSString *  _Nonnull str, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSRange range = [oringinStr rangeOfString:str];
            [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
            [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
            oringinStr = [oringinStr stringByReplacingCharactersInRange:range withString:[weakSelf getStringWithRange:range]];
            
        }];
        
    }else if ([sender isKindOfClass:[NSString class]]) {
        
        NSRange range = [string rangeOfString:sender];
        
        [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
        [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
    }
    return totalStr;
}
- (NSString *)getStringWithRange:(NSRange)range
{
    NSMutableString *string = [NSMutableString string];
    for (int i = 0; i < range.length ; i++) {
        [string appendString:@" "];
    }
    return string;
}

@end
